package async;

import org.apache.jmeter.samplers.Clearable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class AsyncRunInfo implements Clearable {

	public static AsyncRunInfo asyncRunInfo = new AsyncRunInfo();
	private final Logger log = LoggerFactory.getLogger(AsyncRunInfo.class);
	public long sendCount = 0L;
	public long receCount = 0L;
	public long failCount = 0L;
	public long cancCount = 0L;
	public Thread thread;
	public boolean flag = true;

	private AsyncRunInfo() {

	}

	public static AsyncRunInfo getInstance() {

		return AsyncRunInfo.asyncRunInfo;
	}

	public synchronized void sendCount() {
		asyncRunInfo.sendCount++;
	}

	public synchronized void receCount() {
		asyncRunInfo.receCount++;
	}

	public synchronized void failCount() {
		asyncRunInfo.failCount++;
	}

	public synchronized void cancCount() {
		asyncRunInfo.cancCount++;
	}

	public synchronized void start() {

		if (asyncRunInfo.flag) {

			stop();

			asyncRunInfo.thread = new Thread() {
				@Override
				public void run() {
					while (true) {

						try {
							Thread.sleep(10000);
						} catch (Exception e) {
							e.printStackTrace();
						}

						log.info("sendTPS: " + asyncRunInfo.sendCount / 10 + "	receTPS: " + asyncRunInfo.receCount / 10
								+ "	failCount: " + asyncRunInfo.failCount + "	cancCount: " + asyncRunInfo.cancCount);

						asyncRunInfo.sendCount = 0L;
						asyncRunInfo.receCount = 0L;
						asyncRunInfo.failCount = 0L;
						asyncRunInfo.cancCount = 0L;
					}
				}
			};

			asyncRunInfo.flag = false;
			asyncRunInfo.thread.start();

			log.info("AsyncRunInfo Started");
		}
	}

	@SuppressWarnings("deprecation")
	public synchronized void stop() {

		while (asyncRunInfo.thread != null && asyncRunInfo.thread.isAlive()) {
			asyncRunInfo.thread.stop();
			try {
				Thread.sleep(100);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}

			asyncRunInfo.flag = true;
			log.info("AsyncRunInfo Stoped");
		}
	}

	@Override
	public void clearData() {

		asyncRunInfo.sendCount = 0L;
		asyncRunInfo.receCount = 0L;
		asyncRunInfo.failCount = 0L;
		asyncRunInfo.cancCount = 0L;

		asyncRunInfo.start();
	}
}
